<?php

class Reale_Model_NewsMapper 
{
	/**
     * @var Zend_Db_Table_Abstract
     */
    protected $_dbTable;

    /**
     * Specify Zend_Db_Table instance to use for data operations
     * 
     * @param  Zend_Db_Table_Abstract $dbTable 
     * @return Reale_Model_EnquiryMapper
     */
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    /**
     * Get registered Zend_Db_Table instance
     *
     * Lazy loads Reale_Model_DbTable_Enquiry if no instance registered
     * 
     * @return Zend_Db_Table_Abstract
     */
    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Reale_Model_DbTable_News');
        }
        return $this->_dbTable;
    }
    
    /**
     * 
     * Save the news.
     * @param Reale_Model_News $news
     */
    public function save($news){
    	$data = array(
    				'news_title' => $news->getNews_title(),
    				'news_summary' => $news->getNews_summary(),
    				'news_body' => $news->getNews_body(),
    			);
    	
    	$pKey = $this->getDbTable()->insert($data);
    	
    	if($pKey){
    		$news->setNews_id($pKey);
			return true;
    	}
    	return false;
    }
    
    /**
     * 
     * Fetches news.
     * @param Reale_Model_News $news
     * @return Array|NULL
     */
    public function fetch($news,$count=null){
    	$select = $this->getDbTable()->getAdapter()
    				->select()
    				->from('news',
    						array('news_id',
    								'news_date',
    								'news_title',
    								'news_summary', 
    								'news_body'))
    				->order('news_id DESC');
    	
    	if ($count) {
    		$select->limit($count);
    	}
    	return $select->query()
    					   ->fetchAll();
	}				   	
}

